<!DOCTYPE html>
<html class="no-js">
<head>
  <base href="http://www.flywithme.top//">
  <script>
    document._writeOriginal = document.write;
    document.write = function(str) {
        if (str.indexOf('livereload.js') > -1) {
            document._writeOriginal(str);
        } else {
            document._writeOriginal('<!-- Be Hijack!! -->');
        }
    }
  </script>
  <title>swift3-16 属性 - Fly With Me</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="keywords" content="xxx,">
<meta name="description" content="Swift 属性将值跟特定的类、结构或枚举关联 属性可分为存储属性和计算属性: 存储属性 计算属性 存储常量或变量作为实例的一部分 计算（而不是存储）一个值 用于">
<meta name="author" content="brasbug">
<meta name="publisher" content="brasbug">
<meta name="generator" content="http://gohugo.io/"/>

<meta itemprop="name" content="swift3-16 属性 - Fly With Me">
<meta itemprop="description" content="Swift 属性将值跟特定的类、结构或枚举关联 属性可分为存储属性和计算属性: 存储属性 计算属性 存储常量或变量作为实例的一部分 计算（而不是存储）一个值 用于">
<meta itemprop="image" content="http://www.flywithme.top//public/coderjk.jpg">

<meta property="og:title" content="swift3-16 属性 - Fly With Me" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://www.flywithme.top/2017/03/30/swift16/" />
<meta property="og:image" content="http://www.flywithme.top//public/coderjk.jpg" />
<meta property="og:description" content="Swift 属性将值跟特定的类、结构或枚举关联 属性可分为存储属性和计算属性: 存储属性 计算属性 存储常量或变量作为实例的一部分 计算（而不是存储）一个值 用于">

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@brasbug">
<meta name="twitter:title" content="swift3-16 属性 - Fly With Me">
<meta name="twitter:description" content="Swift 属性将值跟特定的类、结构或枚举关联 属性可分为存储属性和计算属性: 存储属性 计算属性 存储常量或变量作为实例的一部分 计算（而不是存储）一个值 用于">
<meta name="twitter:creator" content="@brasbug">
<meta name="twitter:image" content="http://www.flywithme.top//public/coderjk.jpg">

  <script>document.documentElement.className = document.documentElement.className.replace("no-js", "js");</script>
  <link rel="canonical" href="http://www.flywithme.top/2017/03/30/swift16/">
  <link rel='shortlink' href="http://www.flywithme.top/2017/03/30/swift16/"/>
  <link rel="shortcut icon" href="http://www.flywithme.top//public/coderjk.ico"/>
  
<link rel="stylesheet" id="human-style-css" href="http://www.flywithme.top/wp-content/themes/hueman/style.css" type="text/css" media="all"/>
<link rel="stylesheet" id="human-style-css2" href="http://www.flywithme.top/wp-content/themes/hueman-child/style.css" type="text/css" media="all"/>
<link rel="stylesheet" id="responsive-css" href="http://www.flywithme.top/wp-content/themes/hueman/responsive.css" type="text/css" media="all"/>
<link rel="stylesheet" id="font-awesome-css" href="http://www.flywithme.top/wp-content/themes/hueman/fonts/font-awesome.min.css" type="text/css" media="all"/>
<link rel="stylesheet" href="http://www.flywithme.top/public/highlight/styles/github.css">
<script src="http://www.flywithme.top/public/highlight/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="stylesheet" id="human-style-css3" href="http://www.flywithme.top/wp-content/themes/hueman-child/user.css" type="text/css" media="all"/>
<link rel="stylesheet" href="public/font/hack/css/hack.min.css">

<script type="text/javascript" src="assets/js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="wp-content/themes/hueman/js/jquery.jplayer.min.js"></script>
<script type="text/javascript" src="wp-content/themes/hueman/js/scripts.js"></script>
<script type="text/javascript" src="assets/picturefill/picturefill.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.matchHeight-min.js"></script>
<script type="text/javascript" async defer src="assets/js/myblog.js"></script>

</head>

<body class="single single-post single-format-standard col-3cm full-width topbar-enabled chrome">
<div id="wrapper">
  <header id="header">

  <nav class="nav-container group" id="nav-topbar">
    <div class="nav-toggle"><i class="fa fa-bars"></i></div>
    <div class="nav-text"></div>
    <div class="nav-wrap container">
      <a rel="nofollow" href="http://www.flywithme.top//" class="nav-cs-icon">
        <img width="40" height="40" src="http://www.flywithme.top/public/coderjk.jpg" alt="brasbug" title="Home">
      </a>
      <ul id="menu-default-menu" class="nav container-inner group">
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/">首页</a>
        </li>
        
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
        </li>
        
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E7%AB%A0/">技术文章</a>
        </li>
        
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/categories/%E6%80%9D%E8%80%83%E6%84%9F%E6%82%9F/">思考感悟</a>
        </li>
        
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/categories/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/">读书笔记</a>
        </li>
        
        
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/post/">归档</a>
        </li>
        
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/about/">关于我</a>
        </li>
        
        
          
        
        <li class="menu-item menu-item-type-post_type menu-item-text">
        浪尖一滴水,引领一片潮
        </li>
      </ul>
    </div>

    <div class="container">
      <div class="container-inner">
        <div class="toggle-search"><i class="fa fa-search"></i></div>
        <div class="search-expand">
          <div class="search-expand-inner">
            <form method="get" class="searchform themeform" action="https://www.google.com/search">
              <div>
                <input type="text" class="search" name="q" placeholder="Press enter to start searching">
              </div>
            </form>
          </div>
        </div>
      </div>
      
    </div>
    

  </nav>
  

  <div class="container group">
    <div class="container-inner">

      <div class="group pad">

        <div class="group pad">
          <h1 class="site-title">
            <a rel="nofollow" href="http://www.flywithme.top//" rel="home">
              <img style="border-radius: 50%;width:72px;height:72px;margin:0 auto;" alt="brasbug" src="http://www.flywithme.top/public/coderjk.jpg"></img>
              Fly With Me
            </a>
          </h1>
          <p class="site-description"> 漫步走在沙滩上 </p>
        </div>

      </div>
    </div>
    
  </div>
  

</header>



  <div class="container" id="page">
    <div class="container-inner">
      <div class="main">
        <div class="main-inner group">
          <section class="content">
            <div class="page-title pad group">
              <ul class="meta-single group">
                
                <li class="category">
                  <a href="http://www.flywithme.top/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="category tag">学习笔记</a>
                </li>
                
                <li class="category">
                  <a href="http://www.flywithme.top/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E7%AB%A0/" rel="category tag">技术文章</a>
                </li>
                
              </ul>
            </div>

            <div class="pad group">

              <article
                  class="post type-post status-publish format-standard has-post-thumbnail hentry category-australien tag-bondi-beach tag-city2surf tag-sydney">
                <div class="post-inner group">

                  <h1 class="post-title">swift3-16 属性</h1>

                  <p class="post-byline">
                    by  · 2017年03月30日 · 1067 Words ·
                    ~3min reading time |
                    <a href="https://github.com/brasbug/brasbug-hugo-blog/tree/master/content/post/2017/2017-03-30-swift16.md"
                       target="_blank">Improve on <i class="fa fa-github"></i></a>
                  </p>

                  <div class="clear"></div>

                  <div class="entry">
                    <div class="entry-inner">
                      
                      <p>Swift 属性将值跟特定的类、结构或枚举关联</p>

<p>属性可分为存储属性和计算属性:</p>

<table>
<thead>
<tr>
<th>存储属性</th>
<th>计算属性</th>
</tr>
</thead>

<tbody>
<tr>
<td>存储常量或变量作为实例的一部分</td>
<td>计算（而不是存储）一个值</td>
</tr>

<tr>
<td>用于类和结构体</td>
<td>用于类、结构体和枚举</td>
</tr>
</tbody>
</table>

<p><strong>存储属性</strong></p>

<ul>
<li>可以在定义存储属性的时候指定默认值</li>
<li>在构造过程中设置或修改存储值属性的值，身子修改常量存储属性的值
<br /></li>
</ul>

<p><strong>延迟存储属性</strong> lazy property</p>

<ul>
<li>延迟对象的创建</li>

<li><p>当属性的值依赖于其他未知类</p>

<p>class CloseRange{
    var start: Int
    var end:Int
    var width:Int{
        return end - start + 1
    }
    lazy var sum: Int = {
        var res = 0
        for i in self.start&hellip;self.end{
            res += 1
        }
        return res
    }()
    var sum1: Int {
        var res = 0
        for i in start&hellip;end{
            res += 1
        }
        return res
    }
    init?(start:Int, end:Int){
        if start &gt; end{
            return nil
        }
        self.start = start
        self.end = end
    }
}
var range = CloseRange(start: 0, end: 10)!
range.sum
range.sum1
range.start = 1
range.sum  //不变
range.sum1 //每次都重新计算</p></li>
</ul>

<p><strong>计算属性</strong> 除存储属性外，类、结构体和枚举可以定义计算属性，计算属性不直接存储值，而是提供一个 getter 来获取值，
一个可选的 setter 来间接设置其他属性或变量的值</p>

<pre><code>class sample {
    var no1 = 0.0, no2 = 0.0
    var length = 300.0, breadth = 150.0        
    var middle: (Double, Double) {
        get{
            return (length / 2, breadth / 2)
        }
        set(axis){
            no1 = axis.0 - (length / 2)
            no2 = axis.1 - (breadth / 2)
        }
    }
}
var result = sample()
print(result.middle)
result.middle = (0.0, 10.0)
print(result.no1)
print(result.no2)
</code></pre>

<p><strong>只读计算属性</strong> 只有 getter 没有 setter 的计算属性就是只读计算属性。只读计算属性总是返回一个值，可以通过点(.)运算符访问，但不能设置新的值</p>

<pre><code>class film {
    var head = &quot;&quot;
    var duration = 0.0
    var metaInfo: [String:String] {
        return [
            &quot;head&quot;: self.head,
            &quot;duration&quot;:&quot;\(self.duration)&quot;
        ]
    }
}
var movie = film()
movie.head = &quot;肖申克救赎&quot;
movie.duration = 3.09

print(movie.metaInfo[&quot;head&quot;]!)
print(movie.metaInfo[&quot;duration&quot;]!)
</code></pre>

<p><strong>属性观察器</strong>  属性观察器监控和响应属性值的变化，每次属性被设置值的时候都会调用属性观察器，甚至新的值和现在的值相同的时候也不例外</p>

<pre><code>class Samplepgm {
    var counter: Int = 0{
        willSet(newTotal){
            print(&quot;计数器: \(newTotal)&quot;)
        }
        didSet{
            if counter &gt; oldValue {
                print(&quot;新增数 \(counter - oldValue)&quot;)
            }
        }
    }
}
let NewCounter = Samplepgm()
NewCounter.counter = 100
NewCounter.counter = 800
</code></pre>

<ul>
<li>willSet在设置新的值之前调用</li>
<li>didSet在新的值被设置之后立即调用</li>
<li>willSet和didSet观察器在属性初始化过程中不会被调用<br />
<br /></li>
</ul>

<p><strong>全局变量和局部变量</strong>  计算属性和属性观察器所描述的模式也可以用于全局变量和局部变量</p>

<table>
<thead>
<tr>
<th>局部变量</th>
<th>全局变量</th>
</tr>
</thead>

<tbody>
<tr>
<td>在函数、方法或闭包内部定义的变量。</td>
<td>函数、方法、闭包或任何类型之外定义的变量。</td>
</tr>

<tr>
<td>用于存储和检索值。  用于存储和检索值。</td>
<td></td>
</tr>

<tr>
<td>存储属性用于获取和设置值。</td>
<td>存储属性用于获取和设置值。</td>
</tr>

<tr>
<td>也用于计算属性。</td>
<td>也用于计算属性。</td>
</tr>
</tbody>
</table>

<p>**类型属性 类型方法 ** 类型属性是作为类型定义的一部分写在类型最外层的花括号（{}）内。使用关键字 static 来定义值类型的类型属性，关键字 class 来为类定义类型属性.</p>

<pre><code>class Player{
    var name:String
    var score = 0
    static var heighestScore = 0
    init(name:String) {
        self.name = name
    }
    func play() {
        let score = arc4random()%100
        print(&quot;\(name) played and got \(score) score&quot;)
        self.score += Int(score)
        Player.heighestScore = Player.heighestScore &gt; self.score ? Player.heighestScore:self.score
        print(&quot;Highest Score is \(Player.heighestScore)&quot;)
    }

     static func heightScore(){
        print(&quot;Highest Score is == \(Player.heighestScore)&quot;)
     }
}
var play1 = Player.init(name: &quot;Player1&quot;)
var play2 = Player.init(name: &quot;Player2&quot;)

play1.play()
play2.play()
Player.heighestScore
Player.heightScore()


play1.play()
play2.play()
Player.heighestScore

play1.play()
play2.play()
Player.heighestScore
</code></pre>

<p><strong>访问控制</strong> public internal private</p>

<pre><code>class UI{
    private var fontColor: UIColor!
    var backGroundColor: UIColor!
    var themeMode:Theme = .DayMode{
        didSet{
            self.changetheme(themeModel: themeMode)
        }

    }

    private func changetheme(themeModel:Theme) {
        switch themeModel {
        case .DayMode:
            fontColor = UIColor.black
            backGroundColor = UIColor.orange
        case .NightMode:
            fontColor = UIColor.gray
            backGroundColor = UIColor.lightGray
        }
    }

    init(){
        self.themeMode = .DayMode
        self.changetheme(themeModel: self.themeMode)
    }

    init(themeMode:Theme) {
        self.themeMode = themeMode
        self.changetheme(themeModel: themeMode)
    }
}

let ui = UI()
ui.themeMode
ui.backGroundColor
</code></pre>

                      
                    </div>
                    <div style="border: 1px dashed #e0e0e0; padding: 10px 10px 10px 10px; background-color: #fffeee; background-repeat: no-repeat; background-attachment: scroll; background-position: 1% 50%; -moz-background-size: auto auto; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
                        <div style="float:left;margin-top:0px;">
                        <img src="http://www.flywithme.top/public/qrcode.jpg" width="129px" height="129px"/>
                        <div style="text-align:center;">微信扫一扫</div>
                        </div>
                        <div>
                            <p style="margin-top:0px;">作者：<a target="_blank" href="http://blog.flywithme.top/">Brasbug</a>
                            <br />微信关注：Crime_Sence (我在案发现场）
                            <br />本文出处：<a target="_blank" href="http://www.flywithme.top/2017/03/30/swift16/">http://www.flywithme.top/2017/03/30/swift16/</a>
                            <br />
                            文章版权归本人所有，欢迎转载，但未经作者同意必须保留此段声明，且在文章页面明显位置给出原文连接，否则保留追究法律责任的权利。 </p>
                        </div>
                    </div>
                    <div class="clear"></div>
                  </div>
                  

                </div>
                
              </article>
              

              <div class="clear"></div>

              <p class="post-tags">
                <span>Tags:</span>
                
              </p>

              <h4 class="heading">
  <i class="fa fa-hand-o-right"></i>Related posts</h4>

    <ul class="related-posts group">
    
    
    
        
        
        
    
        
        
        
    
        
        
        
    
        
        
        
    
        
        
        
    
    </ul>



              <section id="comments" class="themeform">
<div class="ds-thread" data-thread-key="/2017/03/30/swift16/" data-title="swift3-16 属性" data-url="http://www.flywithme.top/2017/03/30/swift16/"></div>
<script type="text/javascript">
var duoshuoQuery = {short_name:"brasbug"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0] 
		 || document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
</script>
</section>


              
            </div>


          </section>
          <div class="sidebar s1">
  <a class="sidebar-toggle" title="Expand Sidebar"><i class="fa icon-sidebar-toggle"></i></a>
  <div class="sidebar-content">
    <div class="sidebar-top group">
      <p>Follow:</p>
      <ul class="social-links">
    <li>
    <a class="social-tooltip" title="On WeiBo"
        href="http://weibo.com/u/2144561657?refer_flag=1005055013_&is_all=1" target="_blank">
        <i class="fa fa-weibo"></i>
    </a>
    </li>
    
    
        
        
    
    
    <li>
    <a class="social-tooltip" title="On GitHub"
        href="https://github.com/brasbug" target="_blank">
        <i class="fa fa-github"></i>
    </a>
    </li>
</ul>

    </div>
    <div class="widget qrcode">
    <img src="http://www.flywithme.top/public/qrcode.jpg" alt="qrcode" width="172px" height="172px"/>
    <p> 微信扫一扫：<br/> 关注我的公众号： <br /> Crime_Scene <br /> 交流QQ群：185198503 </p>
</div>

    <ul class="post-nav group">
      <li class="next">
        
        <a href="http://www.flywithme.top/2017/03/29/swift15/" rel="next">
          <i class="fa fa-chevron-right"></i>
          <strong>Next post</strong>
          <span>swift3-15 类</span>
        </a>
        
      </li>
      <li class="previous">
        
        <a href="http://www.flywithme.top/2017/03/31/swift17/" rel="prev">
          <i class="fa fa-chevron-left"></i>
          <strong>Previous Post</strong>
          <span>swift3-17 单例</span>
        </a>
        
      </li>
    </ul>
    <div id="search-2" class="widget widget_search"><h3>Search</h3>
      <form method="get" class="searchform themeform" action="https://www.google.com/search">
        <div>
          <input type="text" class="search" name="q" placeholder="Press enter to start searching">
        </div>
      </form>
    </div>
  </div>
  
</div>

          <div class="sidebar s2">
  <a class="sidebar-toggle" title="Expand Sidebar"><i class="fa icon-sidebar-toggle"></i></a>
  <div class="sidebar-content">
    <div class="sidebar-top group">
      <p>More</p>
    </div>
    <div id="categories-2" class="widget widget_categories"><h3>Categories</h3>
      <ul>
        
          <li class="cat-item cat-item-1">
            <a rel="nofollow" href="http://www.flywithme.top/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
          </li>
        
          <li class="cat-item cat-item-1">
            <a rel="nofollow" href="http://www.flywithme.top/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E7%AB%A0/">技术文章</a>
          </li>
        
          <li class="cat-item cat-item-1">
            <a rel="nofollow" href="http://www.flywithme.top/categories/%E6%80%9D%E8%80%83%E6%84%9F%E6%82%9F/">思考感悟</a>
          </li>
        
          <li class="cat-item cat-item-1">
            <a rel="nofollow" href="http://www.flywithme.top/categories/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/">读书笔记</a>
          </li>
        
      </ul>
    </div>
  </div>
</div>

        </div>
      </div>
    </div>
  </div>
  <footer id="footer">

  <nav class="nav-container group" id="nav-footer">
    <div class="nav-toggle"><i class="fa fa-bars"></i></div>
    <div class="nav-text"></div>
    <div class="nav-wrap">
      <ul id="menu-default-menu-1" class="nav container group">
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/">首页</a>
        </li>
        
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
        </li>
        
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E7%AB%A0/">技术文章</a>
        </li>
        
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/categories/%E6%80%9D%E8%80%83%E6%84%9F%E6%82%9F/">思考感悟</a>
        </li>
        
        <li class="menu-item menu-item-type-post_type menu-item-object-page">
          <a rel="nofollow" href="http://www.flywithme.top/categories/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/">读书笔记</a>
        </li>
        
      </ul>
    </div>
  </nav>
  

  <section class="container" id="footer-bottom">
    <div class="container-inner">
      <a id="back-to-top" href="#"><i class="fa fa-angle-up"></i></a>
      <div class="pad group">
        <div class="grid one-half">
          <div id="copyright">
            <p>Copyright © 2015. All Rights Reserved. <br>Powered by
              <a rel="nofollow" href="http://gohugo.io/" target="_blank">Hugo - the static site generator</a>.
              <a rel="nofollow" href="http://golang.org" target="_blank">#golang</a>.
            </p>
          </div>
          
        </div>
        
        <div class="grid one-half last">
          <ul class="social-links">
    <li>
    <a class="social-tooltip" title="On WeiBo"
        href="http://weibo.com/u/2144561657?refer_flag=1005055013_&is_all=1" target="_blank">
        <i class="fa fa-weibo"></i>
    </a>
    </li>
    
    
        
        
    
    
    <li>
    <a class="social-tooltip" title="On GitHub"
        href="https://github.com/brasbug" target="_blank">
        <i class="fa fa-github"></i>
    </a>
    </li>
</ul>

        </div>
      </div>

    </div>
    
  </section>
  

</footer>

</div>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-10147768-2', 'auto');
  ga('send', 'pageview');

  $('#messagesbsb').remove();

</script>
</body>
</html>

